<?php

namespace app\api\service\shop;

use app\admin\model\factor\CarbonFactor;

/**
 * 因子数据库服务类
 */
class CarbonFactorService
{
    /**
     * 获取因子列表
     * @param array $typeId 生命周期
     * @param int $userId 用户ID
     * @param int $page 页码
     * @param int $limit 每页展示条数
     * @param string|null $content 搜索内容
     * @return array|null 返回查询的数据或null
     */
    public function getFactorList(array $typeId, int $userId, int $page, int $limit, string $content = null): ?array
    {
        
        $data = CarbonFactor::where('status', 1)
            ->where(function ($query) use ($content) {
                if ($content) {
                    $query->where('name', 'like', '%' . $content . '%')
                        ->whereOr('sn', $content);
                }
            })
            ->field(['id', 'name', 'lifecycle', 'user_id', 'carbon_factor_result_kg carbon_result', 'unit', 'is_account', 'is_authority', 'sn', 'sales'])
            ->order(['sales' => 'desc', 'id' => 'desc'])
            ->paginate($limit)
            ->each(function ($item) use ($userId) {
                $item->auth = $item->is_authority == 1 ? '权威性认证' : ($item->is_account == 1 ? '核算结果认证' : null);
                $item->append(['company_name']);
                $item->is_collection = !empty($item->collection()->where(['user_id' => $userId, 'factor_id' => $item->id])->count('user_id'));
                unset($item->is_authority, $item->is_account, $item->sales);
            });


        return ['total' => $data->total(), 'row' => $data->items()];
    }
}